import { Command } from '../constant';
import Taro from '@tarojs/taro';
import { Dispatch } from 'typings';
import { IAllReducerProps } from '../types';
import { getReducerData } from '@/redux/store';
import api from 'api';
import { extraPathsValue } from '@/redux/util';

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },

    async page() {
      let { form = {}, boxData = [] } = getData().main || {};
      action.commonChange('main.isLoadingList', true);
      const res = await api.iplandBaseController.treasureBoxPage(form);
      action.commonChange([{ paths: 'main.totalPages', value: (res as any).totalPages }]);
      if (form.pageNum == 0) {
        action.commonChange([
          { paths: 'main.boxData', value: res?.content },
          { paths: 'main.totalPages', value: res?.totalPages },
        ]);
      } else {
        // @ts-ignore
        action.commonChange([{ paths: 'main.boxData', value: boxData.concat(res?.content) }]);
      }
      action.commonChange('main.isLoadingList', false);
    },

    async list() {
      action.commonChange('main.isLoadingList', true);
      const res = await api.iplandBaseController.treasureBoxList();
      action.commonChange([{ paths: 'main.boxData', value: res}]);
      action.commonChange('main.isLoadingList', false);
    },

    /**
    * 查询下一页
    */
    async nextPage() {
      let { form = {}, totalPages } = getData().main || {};
      let num = form.pageNum + 1;
      if (num == totalPages) return;
      dispatch({
        type: Command.commonChange,
        payload: {
          paths: 'main.form.pageNum',
          value: num,
        },
      });
      await this.page();
    },

    async goToWeixinPay(openid: string, boxid) {
      //goodsType 0:魔力币 1:宝箱
      const context = await api.SyntheticRechargeController.iplandPay({ goodsType: 1, id: boxid, openid });
      //@ts-ignore
      const { timeStamp, nonceStr, signType, paySign } = context;
      await Taro.requestPayment({
        timeStamp,
        nonceStr,
        //@ts-ignore
        package: context.package,
        signType,
        paySign,
        success: async (res) => {
          Taro.showToast({
            title: '购买成功!',
            icon: 'none',
          });
          dispatch({
            type: Command.commonChange,
            payload: {
              paths: 'main.form.pageNum',
              value: 0,
            },
          });
          await this.list();
        },
        fail: function (res) { },
      });
    },
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageIGiftpackMain'),
  };
}

//create by moon https://github.com/creasy2010/moon
